package cn.funeralobjects.project.aliyun.ddns.schedule;

import cn.funeralobjects.project.aliyun.ddns.service.DdnsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author FuneralObjects
 * Create date: 2020/11/30 1:53 AM
 */
@Component
@EnableScheduling
public class DdnsSechedule implements SchedulingConfigurer {

    private static final Logger LOGGER = LoggerFactory.getLogger("DDNS-SCHEDULE");

    @Resource
    private DdnsService ddnsService;

    @Value("${ddns.record-file}")
    private String recordFile;

    @Value("${ddns.cron}")
    private String cron;

    @PostConstruct
    private void init() throws IOException {
        File file = new File(recordFile);
        if (!file.exists() || !file.isFile()) {
            LOGGER.info("The file '{}' doesn't exist. Generating..", recordFile);
            ClassPathResource resource = new ClassPathResource("ddns-data-template");
            FileCopyUtils.copy(resource.getInputStream(), new FileOutputStream(file));
        }

    }


    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addCronTask(() -> {
            LOGGER.info("start ddns task");
            ddnsService.update(recordFile, "#");
            LOGGER.info("update done");
        }, cron);

        //update immediately
        ddnsService.update(recordFile, "#");
    }
}
